package de.tudarmstadt.ukp.muip.fibqdojo.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;

/**
 * Abstract class which provides methods for writing data to a XML file.
 * 
 * @author Tobias Horsmann
 */
public abstract class Writer implements IO_Constants {

    protected final String encoding;
    protected final String tokenSeparator;
    protected final String path;

    protected XMLEventWriter eventWriter;
    protected XMLEventFactory eventFactory;

    public Writer(String path, String encoding, String separator) throws ParserConfigurationException,
            FileNotFoundException, XMLStreamException {
        this.path = path;
        this.encoding = encoding;
        this.tokenSeparator = separator;
        initNewXMLDocument();
    }

    private void initNewXMLDocument() throws ParserConfigurationException, FileNotFoundException, XMLStreamException {

        XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(path));
        eventFactory = XMLEventFactory.newInstance();
        StartDocument startDocument = eventFactory.createStartDocument();
        eventWriter.add(startDocument);
        StartElement configStartElement = eventFactory.createStartElement("", "", DATA);
        eventWriter.add(configStartElement);
        createSeperatorEntry();
    }

    private void createSeperatorEntry() throws XMLStreamException {
        eventFactory = XMLEventFactory.newInstance();
        StartElement sElement = eventFactory.createStartElement("", "", SEPARATOR);
        eventWriter.add(sElement);
        Characters characters = eventFactory.createCharacters(tokenSeparator);
        eventWriter.add(characters);
        EndElement eElement = eventFactory.createEndElement("", "", SEPARATOR);
        eventWriter.add(eElement);
    }

    public void close() throws XMLStreamException {
        eventWriter.add(eventFactory.createEndElement("", "", DATA));
        eventWriter.close();
    }
}
